<template>
    <a-modal v-model:visible="visible" :on-before-ok="submit" @cancel="close">
        <template #title>告警配置</template>
        <div>
            <a-form ref="formRef" :model="formData" :rules="formRules">
                <a-form-item field="alertName" label="告警名称">
                    <a-input v-model="formData.alertName"></a-input>
                </a-form-item>
                <a-form-item field="status" label="状态">
                    <a-select v-model="formData.status">
                        <a-option
                            v-for="option in AlertStatusOptions"
                            :key="option.value"
                            :label="option.label"
                            :value="option.value"
                        ></a-option>
                    </a-select>
                </a-form-item>
                <a-form-item
                    field="triggers"
                    label="触发条件"
                    :hide-label="true"
                >
                    <div class="condition-box">
                        <div class="main">
                            <!-- <div class="title">条件</div> -->
                            <div class="main-box">
                                <div
                                    v-for="(
                                        cond, condIndex
                                    ) in formData.triggers"
                                    :key="condIndex"
                                    class="box"
                                >
                                    <div class="item">
                                        <a-row :gutter="24">
                                            <a-col :span="8">
                                                <a-form-item
                                                    :field="
                                                        'triggers.' +
                                                        condIndex +
                                                        '.identifier'
                                                    "
                                                    :hide-label="true"
                                                    :rules="[
                                                        {
                                                            required: true,
                                                            message: '请选择',
                                                        },
                                                    ]"
                                                >
                                                    <a-select
                                                        v-model="
                                                            cond.identifier
                                                        "
                                                        :style="{
                                                            width: '300px',
                                                        }"
                                                        placeholder="请选择"
                                                    >
                                                        <a-option
                                                            v-for="option in formData.productProperties"
                                                            :key="
                                                                option.identifier
                                                            "
                                                            :label="option.name"
                                                            :value="
                                                                option.identifier
                                                            "
                                                        ></a-option>
                                                    </a-select>
                                                </a-form-item>
                                            </a-col>
                                            <a-col :span="8">
                                                <a-form-item
                                                    :field="
                                                        'triggers.' +
                                                        condIndex +
                                                        '.operator'
                                                    "
                                                    :hide-label="true"
                                                    :rules="[
                                                        {
                                                            required: true,
                                                            message: '请选择',
                                                        },
                                                    ]"
                                                >
                                                    <a-select
                                                        v-model="cond.operator"
                                                        :style="{
                                                            width: '300px',
                                                        }"
                                                        placeholder="请选择"
                                                    >
                                                        <a-option
                                                            v-for="option in comparators"
                                                            :key="option.value"
                                                            :label="option.name"
                                                            :value="
                                                                option.value
                                                            "
                                                        ></a-option>
                                                    </a-select>
                                                </a-form-item>
                                            </a-col>
                                            <a-col :span="8">
                                                <a-form-item
                                                    :field="
                                                        'triggers.' +
                                                        condIndex +
                                                        '.value'
                                                    "
                                                    :hide-label="true"
                                                    :rules="[
                                                        {
                                                            required: true,
                                                            message: '请填写',
                                                        },
                                                    ]"
                                                >
                                                    <a-input
                                                        v-model="cond.value"
                                                        placeholder="请填写"
                                                    ></a-input>
                                                </a-form-item>
                                            </a-col>
                                        </a-row>
                                    </div>
                                    <a-button
                                        type="dashed"
                                        status="danger"
                                        @click="
                                            handleRemoveCondition(
                                                formData,
                                                condIndex
                                            )
                                        "
                                    >
                                        <template #icon>
                                            <icon-delete />
                                        </template>
                                    </a-button>
                                </div>
                            </div>
                        </div>

                        <a-button
                            type="primary"
                            size="small"
                            style="margin-top: 12px"
                            @click="handleAddCondition(formData)"
                            >新增条件
                        </a-button>
                    </div>
                </a-form-item>
            </a-form>
        </div>
    </a-modal>
</template>

<script lang="ts" setup>
    import { ref, reactive, PropType } from 'vue';
    import { pick } from 'lodash';
    import { useI18n } from 'vue-i18n';
    import { AlertStatusOptions } from './const';
    import {
        productAlertDetail,
        addProductAlert,
        editProductAlert,
        getProductModelList,
    } from './service';

    const { t } = useI18n();

    const props = defineProps({
        title: {
            type: String,
            default: '',
        },
        type: {
            type: String as PropType<'ADD' | 'EDIT'>,
            default: 'ADD',
        },
        productId: {
            type: String,
            default: '',
        },
        id: {
            type: String,
            default: '',
        },
    });
    const emit = defineEmits(['submit']);

    const visible = ref(false);
    const formRef = ref();
    const formData = reactive({
        productId: props.productId,
        alertName: '',
        status: 1,
        triggers: Array({
            id: Number,
            identifier: '',
            name: '',
            value: '',
            operator: '',
            type: '1',
        }),
        productProperties: Array({
            id: Number,
            identifier: '',
            name: '',
        }),
    });
    const triggersValid = (value, callback) => {
        if (value.length < 1) {
            callback('至少添加一个触发条件');
        } else {
            callback();
        }
    };
    const formRules = {
        alertName: [
            {
                required: true,
                message: '请输入名称',
            },
        ],
        triggers: [
            {
                require: true,
            },
            {
                validator: triggersValid,
            },
        ],
    };
    // 条件
    const comparators = ref([
        {
            name: '大于',
            value: '>',
        },
        {
            name: '大于等于',
            value: '>=',
        },
        {
            name: '等于',
            value: '==',
        },
        {
            name: '小于',
            value: '<',
        },
        {
            name: '小于等于',
            value: '<=',
        },
        {
            name: '不等于',
            value: '!=',
        },
    ]);

    // 新增条件
    const handleAddCondition = (item: any) => {
        if (!item.triggers) item.triggers = [];
        item.triggers.push({});
        formRef.value.validateField('triggers');
    };
    // 删除条件
    const handleRemoveCondition = (item: any, index: number) => {
        item.triggers.splice(index, 1);
    };

    async function open() {
        const { result: productProperties } = await getProductModelList({
            productId: formData.productId,
        });
        if (props.type === 'EDIT') {
            const { result } = await productAlertDetail({
                id: props.id,
            });
            Object.assign(
                formData,
                pick(result, ['id', 'alertName', 'status', 'triggers'])
            );
        } else {
            formData.triggers = [];
        }
        formData.productProperties = productProperties;

        visible.value = true;
    }

    function close() {
        formRef.value.resetFields();
        visible.value = false;
    }

    async function submit() {
        const res = await formRef.value.validate();
        if (res) {
            return false;
        }
        const { productProperties, ...payload } = formData;
        // const payload = (({ productProperties, ...noProductProperties }) => noProductProperties)(formData);
        if (props.type === 'ADD') {
            await addProductAlert(payload);
        } else {
            await editProductAlert(payload);
        }
        emit('submit');
        formRef.value.resetFields();
        return true;
    }

    defineExpose({
        open,
    });
</script>

<style scoped lang="less">
    .condition-box {
        width: 100%;
        //background-color: #f2f2f2;
        //padding: 15px;
        //border-top: 1px solid #d9d9d9;
        .main {
            border: 2px dashed rgb(217 217 217);

            .title {
                padding: 5px 15px;
                color: #333;
                font-weight: 600;
                border-bottom: 1px solid rgb(217 217 217);
            }

            .main-box {
                padding: 10px;

                .box {
                    display: flex;
                    align-items: center;
                    margin: 10px 0;

                    .item {
                        display: flex;
                        flex: 1;
                        align-items: center;
                        justify-content: space-between;
                        margin-top: 0;

                        .param-item {
                            margin-bottom: 8px;
                        }
                    }

                    .item-span {
                        margin: 0 5px !important;
                    }

                    .arco-btn {
                        margin-bottom: 20px;
                        margin-left: 10px;
                    }
                    // .el-button {
                    //   width: 50px;
                    // }
                }
            }
        }
    }
</style>
